//
//  CLMainViewController.m
//  JG
//
//  Created by 程龙 on 2023/7/28.
//

#import "CLMainViewController.h"
#import <WebKit/WebKit.h>
#import "CLButton.h"
#import "CLScanViewController.h"
#import "CLScanView.h"
#import <TZImagePickerController/TZImagePickerController.h>
@interface CLMainViewController ()<WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate,AMapLocationManagerDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    WKWebViewConfiguration *config;
    WKWebView *wView;
}
@property (nonatomic, strong) UIBarButtonItem *homeItem;
@property (nonatomic, strong) UIBarButtonItem *exitItem;
@property (nonatomic, strong) UIButton *logoutBtn;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@end

@implementation CLMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.gk_navTitle = @"";
    self.gk_navRightBarButtonItems = @[self.exitItem, self.homeItem];
    
    
    
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.path=url_update;
        request.methodType=ZBMethodTypePOST;
        request.parameters = @{@"currentVersion":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                               @"device":@"iOS",
                               @"model":[[UIDevice currentDevice] model],
                               @"workCode":[CLData sharedClass].jobNumber,

        };
    }  success:^(id responseObject,ZBURLRequest * request){
        if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
            if([CLTool isNullToDictionary:responseObject[@"data"]] == YES){
                CLLog(@"没有新版本");
                return;
            }

            if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"isForce"]] isEqualToString:@"1"] ){
                Dialog()
                //出现动画
                    .wShowAnimationSet(AninatonZoomIn)
                //消失动画
                    .wHideAnimationSet(AninatonZoomOut)

                    .wEventOKFinishSet(^(id anyID, id otherData) {
                        NSString * _dataString = [[NSString alloc] initWithData:[responseObject[@"data"][@"downloadurl"] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];

                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_dataString] options:nil completionHandler:^(BOOL success) {

                        }];
                    })
                    .wTitleSet(@"发现新版本，建议立即更新")
                    .wMessageSet(responseObject[@"data"][@"features"])
                    .wOKTitleSet(@"更新")
                    .wMessageColorSet(DialogColor(0x333333))
                    .wTitleColorSet(DialogColor(0x666666))
                    .wOKColorSet([UIColor orangeColor])

                    .wTitleFontSet(15)
                    .wShadowShowSet(YES)
                    .wShadowCanTapSet(NO)
                    .wAutoCloseSet(NO)
                    .wTagSet(999)
                    .wTypeSet(DialogTypeNornal).wStartView(self.view);
            }else{
                Dialog()
                //出现动画
                    .wShowAnimationSet(AninatonZoomIn)
                //消失动画
                    .wHideAnimationSet(AninatonZoomOut)
                    .wEventCancelFinishSet(^(id anyID, id otherData) {
                        [self maskViewAction];
                    })
                    .wEventOKFinishSet(^(id anyID, id otherData) {
                        NSString * _dataString = [[NSString alloc] initWithData:[responseObject[@"data"][@"downloadurl"] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];

                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_dataString] options:nil completionHandler:^(BOOL success) {

                        }];
                    })
                    .wTitleSet(@"发现新版本，建议立即更新")
                    .wMessageSet(responseObject[@"data"][@"features"])
                    .wOKTitleSet(@"更新")
                    .wCancelTitleSet(@"取消")
                    .wMessageColorSet(DialogColor(0x333333))
                    .wTitleColorSet(DialogColor(0x666666))
                    .wOKColorSet([UIColor orangeColor])
                    .wCancelColorSet([UIColor blueColor])
                    .wTitleFontSet(15)
                    .wTypeSet(DialogTypeNornal).wStartView(self.view);
            }
        }else{
            [CLTool cl_showFail:responseObject[@"msg"] block:^{

            }];
        }


    } failure:^(NSError * _Nullable error) {
        [CLTool cl_showFail:@"请求错误" block:^{

        }];
    } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
        NSLog(@"请求完成");
    }];
    
    
    
    config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *controller = [[WKUserContentController alloc] init];
    
    NSString * string1 = @"OpenScan";
    [controller addScriptMessageHandler:self name:string1];
    
    NSString * string2 = @"nativeCallback";
    [controller addScriptMessageHandler:self name:string2];
    
    NSString * string3 = @"getHongTuLocation";
    [controller addScriptMessageHandler:self name:string3];
    
    
    NSString * string4 = @"openAPPCamera";
    [controller addScriptMessageHandler:self name:string4];

        
    
    config.userContentController = controller;
    
    wView = [[WKWebView alloc] initWithFrame:CGRectMake(0, CL_SizeStatusBarAndNavigationBarHeight, CLWIDTH, CLHEIGHT-CL_SizeStatusBarAndNavigationBarHeight) configuration:config];
    wView.UIDelegate = self;
    wView.navigationDelegate = self;
    wView.allowsBackForwardNavigationGestures = YES;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.address]];

    [wView loadRequest:request];
    [self.view addSubview:wView];
    
    //    [wView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    //    [wView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    
    CLLog(@"请求地址：%@",self.address);
    
//    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"ceshicamera" ofType:@"html"];
//
//     NSURL *fileUrl = [NSURL fileURLWithPath:htmlPath];
//     [wView loadFileURL:fileUrl allowingReadAccessToURL:fileUrl];
//    [self.view addSubview:wView];
    
    
    self.maskView = [[UIView alloc]init];
    self.maskView.frame = CGRectMake(0, 0, CLWIDTH, CLHEIGHT);
    self.maskView.backgroundColor = [UIColor blackColor];
    self.maskView.alpha = 0.3;
    self.maskView.userInteractionEnabled = YES;
    UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(maskViewAction)];
    [self.maskView addGestureRecognizer:ges];
    [self.view addSubview:self.maskView];
    
    
    self.logoutBtn = [UIButton new];
    self.logoutBtn.frame = CGRectMake(CLWIDTH-100*CLSCALE, CL_SizeStatusBarAndNavigationBarHeight, 90*CLSCALE, 30*CLSCALE);
    [self.logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [self.logoutBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.logoutBtn.titleLabel.font = CLFONT(10);
    self.logoutBtn.backgroundColor = [UIColor whiteColor];
    [self.logoutBtn jk_cornerRadius:5*CLSIZE strokeSize:0 color:[UIColor blackColor]];
    [self.logoutBtn addTarget:self action:@selector(logoutAction) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:self.logoutBtn];
    
    
    [self.maskView setHidden:YES];
    [self.logoutBtn setHidden:YES];
    
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}
//#pragma mark - KVO
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"title"]) {
//        self.gk_navTitle = wView.title;
//    }else if ([keyPath isEqualToString:@"canGoBack"]) {
//        if ([wView canGoBack]) {
//            self.gk_interactivePopDisabled = YES;
//        }else {
//            self.gk_interactivePopDisabled = NO;
//        }
//    }
//}
// 重写下面的方法，拦截点击返回
- (BOOL)navigationShouldPopOnClick {
    [self maskViewAction];
    // do something
    if (wView.canGoBack) {
        [wView goBack];
        
    }else{
        
    }
    
    return NO;
}
// 重写下面的方法，拦截手势返回
- (BOOL)navigationShouldPopOnGesture {
    [self maskViewAction];
    // do something
    if (wView.canGoBack) {
        [wView goBack];
        
    }else{
        
    }
    return NO;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSString * string1 = @"OpenScan";
    if ([message.name isEqualToString:string1]) {
        CLScanViewController *vc = [[CLScanViewController alloc]init];
        vc.block = ^(NSString * _Nonnull _str) {
            NSLog(@"=======%@",_str);
            [self->wView evaluateJavaScript: [NSString stringWithFormat:@"CloseScan('%@')",_str]
                       completionHandler:^(id response, NSError * error) {
                    NSLog(@"response: %@, \nerror: %@", response, error);
             }];
        };
        [self.navigationController pushViewController:vc animated:YES];


        
        

//        CLScanView *qrcodeView = [[CLScanView alloc] initWithFrame:self.view.bounds];
//        qrcodeView.backQRCodeURL = ^(NSString *stringValue) {
//            [self->wView evaluateJavaScript: [NSString stringWithFormat:@"CloseScan('%@')",stringValue]
//                    completionHandler:^(id response, NSError * error) {
//                 NSLog(@"response: %@, \nerror: %@", response, error);
//          }];
//
//            [qrcodeView removeFromSuperview];
//        };
//        qrcodeView.backfailure = ^{
//
//        };
//        [self.view addSubview:qrcodeView];
    }

    
    
//    [CLTool cl_showSuccess:[NSString stringWithFormat:@"js调用ios成功 %@",message.name] block:^{
//
//    }];
    
    
    NSString * string3 = @"getHongTuLocation";
    if ([message.name isEqualToString:string3]) {
        self.locationManager = [[AMapLocationManager alloc] init];
        self.locationManager.delegate = self;
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        //   定位超时时间，最低2s，此处设置为2s
        self.locationManager.locationTimeout =2;
        //   逆地理请求超时时间，最低2s，此处设置为2s
        self.locationManager.reGeocodeTimeout = 2;
        
        // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
                
                if (error)
                {
                    NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                    if (error.code == AMapLocationErrorCanceled)
                    {
                        NSLog(@"取消定位" );
                        
                        return;
                    }
                    
                    [CLTool cl_showFail:[NSString stringWithFormat:@"定位失败 %ld  %@",(long)error.code, error.localizedDescription] block:^{

                    }];
//
                    
                    NSDictionary *tmpDic = @{@"data":@{
                        @"address":@"",
                        @"latitude":@"",
                        @"longitude":@""
                    },
                    @"msg":@"定位失败",
                    @"type":@"E"
                                             
                    };
                    
                    
                    NSError *error = nil;
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmpDic options:0 error:&error];
                    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                    
                    [self->wView evaluateJavaScript: [NSString stringWithFormat:@"locationInfo('%@')",jsonString]
                               completionHandler:^(id response1, NSError * error1) {
                            NSLog(@"response: %@, \nerror: %@", response1, error1);
                        if (error1)
                        {
                            [CLTool cl_showFail:[NSString stringWithFormat:@"上报位置失败 %ld  %@",(long)error1.code, error1.localizedDescription] block:^{
                        
                            }];
                        }else{
//                            [CLTool cl_showSuccess:[NSString stringWithFormat:@"上报位置成功 %@",regeocode.formattedAddress] block:^{
//
//                            }];
                        }
                     }];
                    
                    if (error.code == AMapLocationErrorLocateFailed)
                    {
                        return;
                    }
                }

    //            NSLog(@"location:%@", location);
            NSLog(@"纬度:%f", location.coordinate.latitude);
            NSLog(@"经度:%f", location.coordinate.longitude);
                
                if (regeocode)
                {
                  //  NSLog(@"reGeocode:%@", regeocode);
                    NSLog(@"详细位置:%@", regeocode.formattedAddress);
                    
//                    [CLTool cl_showSuccess:[NSString stringWithFormat:@"定位成功  %@",regeocode.formattedAddress] block:^{
//
//                    }];
                    
                    NSDictionary *tmpDic = @{@"data":@{
                        @"address":regeocode.formattedAddress,
                        @"latitude":@(location.coordinate.latitude),
                        @"longitude":@(location.coordinate.longitude)
                    },
                    @"msg":@"定位成功",
                    @"type":@"S"
                                             
                    };
                    
                    
                    NSError *error = nil;
                    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmpDic options:0 error:&error];
                    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

                    
                    [self->wView evaluateJavaScript: [NSString stringWithFormat:@"locationInfo('%@')",jsonString]
                               completionHandler:^(id response1, NSError * error1) {
                            NSLog(@"response: %@, \nerror: %@", response1, error1);
                        if (error1)
                        {
                            [CLTool cl_showFail:[NSString stringWithFormat:@"上报位置失败 %ld  %@",(long)error1.code, error1.localizedDescription] block:^{
                        
                            }];
                        }else{
//                            [CLTool cl_showSuccess:[NSString stringWithFormat:@"上报位置成功 %@",regeocode.formattedAddress] block:^{
//
//                            }];
                        }
                     }];
                }else{
                    
                }
            }];
    }
    
    NSString * string4 = @"openAPPCamera";
    if ([message.name isEqualToString:string4]) {
        NSLog(@"-------%@",message.body);
        NSData *data = [message.body dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@", dict); // {name = Jack; age = 30; gender = male;}
        
        if ([[NSString stringWithFormat:@"%@",dict[@"facing"]] containsString:@"0"])  {
            NSLog(@"后置");
            self.imagePickerVc.cameraDevice=UIImagePickerControllerCameraDeviceRear;
        }else{
            NSLog(@"前置");

            self.imagePickerVc.cameraDevice=UIImagePickerControllerCameraDeviceFront;
        }
        
        [self takePhoto];
    }
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        if ([challenge previousFailureCount] == 0) {
            
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
            
        } else {
            
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
            
        }
        
    } else {
        
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        
    }
}
/* 在收到响应后，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    
    
    CLLog(@"跳转的地址%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
- (UIBarButtonItem *)homeItem {
    if (!_homeItem) {
        CLButton *btn = [CLButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"首页"] forState:UIControlStateNormal];
        [btn addTarget:self action: @selector(homeAction) forControlEvents: UIControlEventTouchDown];
        btn.imageRect = CGRectMake(10, 10, 24, 24);
        
        _homeItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _homeItem;
}

- (UIBarButtonItem *)exitItem {
    if (!_exitItem) {
        CLButton *btn = [CLButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
        [btn addTarget:self action: @selector(exitAction) forControlEvents: UIControlEventTouchDown];
        btn.imageRect = CGRectMake(10, 10, 24, 24);
        
        _exitItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _exitItem;
}
- (void)homeAction{
//    self.locationManager = [[AMapLocationManager alloc] init];
//    self.locationManager.delegate = self;
//    // 带逆地理信息的一次定位（返回坐标和地址信息）
//    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//    //   定位超时时间，最低2s，此处设置为2s
//    self.locationManager.locationTimeout =2;
//    //   逆地理请求超时时间，最低2s，此处设置为2s
//    self.locationManager.reGeocodeTimeout = 2;
//    
//    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
//    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//            
//            if (error)
//            {
//                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//                
//                if (error.code == AMapLocationErrorCanceled)
//                {
//                    NSLog(@"取消定位" );
//                    
//                    return;
//                }
//                
//                
//                [CLTool cl_showFail:[NSString stringWithFormat:@"定位失败 %ld  %@",(long)error.code, error.localizedDescription] block:^{
//
//                }];
////
//                
//                NSDictionary *tmpDic = @{@"data":@{
//                    @"address":@"",
//                    @"latitude":@"",
//                    @"longitude":@""
//                },
//                @"msg":@"定位失败",
//                @"type":@"E"
//                                         
//                };
//                
//                
//                NSError *error = nil;
//                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmpDic options:0 error:&error];
//                NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//                
//                [self->wView evaluateJavaScript: [NSString stringWithFormat:@"locationInfo('%@')",jsonString]
//                           completionHandler:^(id response1, NSError * error1) {
//                        NSLog(@"response: %@, \nerror: %@", response1, error1);
//                    if (error1)
//                    {
//                        [CLTool cl_showFail:[NSString stringWithFormat:@"上报位置失败 %ld  %@",(long)error1.code, error1.localizedDescription] block:^{
//                    
//                        }];
//                    }else{
////                            [CLTool cl_showSuccess:[NSString stringWithFormat:@"上报位置成功 %@",regeocode.formattedAddress] block:^{
////
////                            }];
//                    }
//                 }];
//                
//                if (error.code == AMapLocationErrorLocateFailed)
//                {
//                    return;
//                }
//            }
//
////            NSLog(@"location:%@", location);
//        NSLog(@"纬度:%f", location.coordinate.latitude);
//        NSLog(@"经度:%f", location.coordinate.longitude);
//            
//            if (regeocode)
//            {
//              //  NSLog(@"reGeocode:%@", regeocode);
//                NSLog(@"详细位置:%@", regeocode.formattedAddress);
//                
//                [CLTool cl_showSuccess:[NSString stringWithFormat:@"定位成功  %@",regeocode.formattedAddress] block:^{
//            
//                }];
//                
//                NSDictionary *tmpDic = @{@"data":@{
//                    @"address":regeocode.formattedAddress,
//                    @"latitude":@(location.coordinate.latitude),
//                    @"longitude":@(location.coordinate.longitude)
//                },
//                @"msg":@"定位成功",
//                @"type":@"S"
//                                         
//                };
//                
//                
//                NSError *error = nil;
//                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tmpDic options:0 error:&error];
//                NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//
//                
//                [self->wView evaluateJavaScript: [NSString stringWithFormat:@"locationInfo('%@')",jsonString]
//                           completionHandler:^(id response1, NSError * error1) {
//                        NSLog(@"response: %@, \nerror: %@", response1, error1);
//                    if (error1)
//                    {
//                        [CLTool cl_showFail:[NSString stringWithFormat:@"上报位置失败 %ld  %@",(long)error1.code, error1.localizedDescription] block:^{
//                    
//                        }];
//                    }else{
////                            [CLTool cl_showSuccess:[NSString stringWithFormat:@"上报位置成功 %@",regeocode.formattedAddress] block:^{
////
////                            }];
//                    }
//                 }];
//            }else{
//                
//            }
//        }];
//    
//    return;
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.path=url_token;
        request.methodType=ZBMethodTypePOST;
    }  success:^(id responseObject,ZBURLRequest * request){
        if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
            [CLData sharedClass].token = responseObject[@"data"][@"token"];
            
            NSString *tmpStr = [CLTool cl_getUser:@"jobNumber"];
            [CLData sharedClass].jobNumber = tmpStr;
            if(tmpStr.length != 0){
                
                [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                    request.path=url_login;
                    request.methodType=ZBMethodTypePOST;
                    request.parameters = @{@"workCode":[CLData sharedClass].jobNumber};
                    request.userInfo = @{@"type":@"999"};
                }  success:^(id responseObject,ZBURLRequest * request){
                    if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                        [CLData sharedClass].homeUrl = responseObject[@"data"][@"url"];
                        
                        WKNavigation *navigation = [self->wView goBack];
                        NSInteger offset = 1;
                        while (!navigation)
                        {
                            offset++;
                            if (self->wView.backForwardList.backList.count >= offset)
                            {
                                WKBackForwardListItem *item1 = [self->wView.backForwardList itemAtIndex:-offset];
                                navigation = [self->wView goToBackForwardListItem:item1];
                            }
                            else
                            {
                                break;
                            }
                        }
                        
                        [self maskViewAction];
                        
                        NSMutableURLRequest *requestWeb = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[CLData sharedClass].homeUrl]];
                        
                        [self->wView loadRequest:requestWeb];
                    }else{
                        [CLTool cl_showFail:responseObject[@"msg"] block:^{
                            
                        }];
                    }
                    
                    
                } failure:^(NSError * _Nullable error) {
                    [CLTool cl_showFail:@"请求错误" block:^{
                        
                    }];
                } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                    NSLog(@"请求完成");
                }];
                
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }else{
            [CLTool cl_showFail:responseObject[@"msg"] block:^{
                
            }];
        }
        
        
    } failure:^(NSError * _Nullable error) {
        [CLTool cl_showFail:@"请求错误" block:^{
            
        }];
    } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
        NSLog(@"请求完成");
    }];
    
    
    
    
}
- (void)exitAction{
    if([self.logoutBtn isHidden] == YES){
        [self.maskView setHidden:NO];
        [self.logoutBtn setHidden:NO];
    }else{
        [self.maskView setHidden:YES];
        [self.logoutBtn setHidden:YES];
    }
    
    
}
- (void)logoutAction{
    
    Dialog()
    //出现动画
        .wShowAnimationSet(AninatonZoomIn)
    //消失动画
        .wHideAnimationSet(AninatonZoomOut)
        .wEventCancelFinishSet(^(id anyID, id otherData) {
            [self maskViewAction];
        })
        .wEventOKFinishSet(^(id anyID, id otherData) {
            
            [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                request.path=url_token;
                request.methodType=ZBMethodTypePOST;
            }  success:^(id responseObject,ZBURLRequest * request){
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                    [CLData sharedClass].token = responseObject[@"data"][@"token"];
                    
                    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                        request.path=url_logout;
                        request.methodType=ZBMethodTypeGET;
                        request.userInfo = @{@"type":@"888"};
                        request.parameters = @{@"service":url_server,
                                               @"logintype":@"1",
                                               @"e9timestamp":[NSString jk_UUIDTimestamp]
                                               
                        };
                    }  success:^(id responseObject,ZBURLRequest * request){
                        
                        [CLTool cl_saveUser:@"" key:@"jobNumber"];
                        [CLData sharedClass].jobNumber = @"";
                        
                        [self maskViewAction];
                        [self.navigationController popViewControllerAnimated:YES];
                        
                        
                    } failure:^(NSError * _Nullable error) {
                        [CLTool cl_showFail:@"请求错误" block:^{
                            
                        }];
                    } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                        NSLog(@"请求完成");
                    }];
                    
                }else{
                    [CLTool cl_showFail:responseObject[@"msg"] block:^{
                        
                    }];
                }
            } failure:^(NSError * _Nullable error) {
                [CLTool cl_showFail:@"请求错误" block:^{
                    
                }];
            } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                NSLog(@"请求完成");
            }];
            

            
            
        })
        .wTitleSet(@"温馨提示")
        .wMessageSet(@"是否确认退出登录")
        .wOKTitleSet(@"确认")
        .wCancelTitleSet(@"取消")
        .wMessageColorSet(DialogColor(0x333333))
        .wTitleColorSet(DialogColor(0x666666))
        .wOKColorSet([UIColor orangeColor])
        .wCancelColorSet([UIColor blueColor])
        .wTitleFontSet(15)
        .wTypeSet(DialogTypeNornal).wStart();
}
- (void)maskViewAction{
    [self.maskView setHidden:YES];
    [self.logoutBtn setHidden:YES];
}
//开始加载

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"开始加载网页");
    
    [CLTool cl_showLoading];
    
}
//加载完成

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    NSLog(@"加载完成");
    
    [CLTool cl_closeWithshowView];
    
}
//加载失败

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSLog(@"加载失败");
    
    [CLTool cl_showFail:@"加载失败" block:^{
        
    }];
    
}
#pragma mark -  Alert弹窗
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message ? : @"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -  Confirm弹框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message ? : @"" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }];
    
    UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -  TextInput弹框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text ? : @"");
    }];
    [alertController addAction:action];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager*)locationManager{
    [locationManager requestWhenInUseAuthorization];// 项目使用期间使用位置信息  可以更换
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (reGeocode)
      {
          NSLog(@"当前地址信息:%@%@%@%@%@%@", reGeocode.province,reGeocode.city,reGeocode.district,reGeocode.street,reGeocode.number,reGeocode.AOIName);
      }
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self->wView evaluateJavaScript: [NSString stringWithFormat:@"cameraImgStream('%@')",@"cancel"]
                       completionHandler:^(id response, NSError * error) {
                    NSLog(@"response: %@, \nerror: %@", response, error);
                if (error)
                {

                }else{

                }
             }];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else {
        [self pushImagePickerController];
    }
}
// 调用相机
- (void)pushImagePickerController {


    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];

        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        _imagePickerVc.sourceType=UIImagePickerControllerSourceTypeCamera;//设置image picker的来源，这里设置为摄像头
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [CLTool cl_showLoading];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    [self->wView evaluateJavaScript: [NSString stringWithFormat:@"cameraImgStream('%@')",encodedImageStr]
               completionHandler:^(id response, NSError * error) {
            NSLog(@"response: %@, \nerror: %@", response, error);
        if (error)
        {
            [CLTool cl_showFail:[NSString stringWithFormat:@"失败 %ld  %@",(long)error.code, error.localizedDescription] block:^{
        
            }];
        }else{
            [CLTool cl_showSuccess:[NSString stringWithFormat:@"成功"] block:^{

            }];
        }
     }];
    
    

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];

    [self->wView evaluateJavaScript: [NSString stringWithFormat:@"cameraImgStream('%@')",@"cancel"]
               completionHandler:^(id response, NSError * error) {
            NSLog(@"response: %@, \nerror: %@", response, error);
        if (error)
        {

        }else{

        }
     }];
}

@end
